package com.software.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class PlayMediaService extends Service {

    private MediaPlayer player;

    public PlayMediaService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 播放
        String media = intent.getStringExtra("media");
        if (media.equals("play")) {
            start();
        } else if(media.equals("pause")) {
            // 暂停
            pause();
        } else if (media.equals("stop")) {
            // 停止
            stop();
        }


        return super.onStartCommand(intent, flags, startId);
    }

    private void stop() {
        if (player != null && player.isPlaying()) {
            //  停止
            player.stop();
            // 重置
            player.reset();
            // 释放资源
            player.release();
        }
    }

    private void pause() {
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    private void start() {
        if (player == null) {
            player = MediaPlayer.create(getApplicationContext(), R.raw.music);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stop();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}